<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2018/4/2
 * Time: 15:21
 */

class CompanyController
{

    protected $payurl = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
    protected $appid; //appid
    protected $mchid;
    protected $signkey;//支付密钥
    protected $cacab =  [];

    public function __construct(){

        $this->appid     =  '**********';
        $this->mchid     =   '*********';
        $this->signkey   =   '*********';
        //必填
        $this->cacab     =[
            'api_cert'=>getcwd().'/certs/apiclient_cert.pem',
            'api_key'=> getcwd().'/certs/apiclient_key.pem',
            'api_ca'=>  getcwd().'/certs/rootca.pem',
        ];
    }

    //$data 要传递的参数， $wxchat微信企业支付等信息
    /** $data 格式如下
     *  $data = array(
    'userid' //申请退款者ID
    'openid' //退款者openid
    'refundid' //退款申请ID
    'money' //退款金额
    'desc'  //退款描述
    );
     *
     */

    public function wxbuild($data, $wxchat=[]){
        //判断有没有CA证书及支付信息
        if(empty($wxchat)){
            $wxchat['appid'] = $this->appid;
            $wxchat['mchid'] = $this->mchid;

            $wxchat['api_cert'] = $this->cacab['api_cert'];
            $wxchat['api_key'] = $this->cacab['api_key'];
            $wxchat['api_ca'] = $this->cacab['api_ca'];
        }
        //请求参数
        $webdata = array(
            'mch_appid' => $wxchat['appid'],
            'mchid'     => $wxchat['mchid'],
            'nonce_str' => md5(time()), 'partner_trade_no'  => time().'s'.$data['userid'], //商户订单号，需要唯一
            'openid'    => $data['openid'],
            'check_name'=> 'NO_CHECK', //OPTION_CHECK不强制校验真实姓名, FORCE_CHECK：强制 NO_CHECK：
            'amount'    => $data['money'] * 100, //付款金额单位为分
            'desc'      => empty($data['desc'])? '退款' : $data['desc'],
            'spbill_create_ip' => '', #服务器ip 客户端ip 其实都可以 我这里涂稳 使用的是服务器ip
        );

        foreach ($webdata as $k => $v) {
            $tarr[] =$k.'='.$v;
        }
        //ascii 排序
        sort($tarr,SORT_REGULAR);

        $sign = implode($tarr, '&');
        $sign .= '&key='.$this->signkey;

        $webdata['sign']=strtoupper(md5($sign));    #生成签名
        //转换为xml格式
        $wget = $this->array2xml($webdata);

        $res = $this->http_post($this->payurl, $wget, $wxchat);
       
        if(!$res){
            return array('status'=>1, 'msg'=>"Can't connect the server" );
        }

        $content = simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA);

        if(strval($content->return_code) == 'FAIL'){
            return array('status'=>1, 'msg'=>strval($content->return_msg));
        }

        if(strval($content->result_code) == 'FAIL'){
            return array('status'=>1, 'msg'=>strval($content->err_code),':'.strval($content->err_code_des));
        }
        $rdata = array(
            'mch_appid'        => strval($content->mch_appid),
            'mchid'            => strval($content->mchid),
            'device_info'      => strval($content->device_info),
            'nonce_str'        => strval($content->nonce_str),
            'result_code'      => strval($content->result_code),
            'partner_trade_no' => strval($content->partner_trade_no),
            'payment_no'       => strval($content->payment_no),
            'payment_time'     => strval($content->payment_time),
        );
        return $rdata;
    }

    /**
     * 将一个数组转换为 XML 结构的字符串
     * @param array $arr 要转换的数组
     * @param int $level 节点层级, 1 为 Root.
     * @return string XML 结构的字符串
     */
    public function array2xml($arr, $level = 1) {
        $s = $level == 1 ? "<xml>" : '';
        foreach($arr as $tagname => $value) {
            if (is_numeric($tagname)) {
                $tagname = $value['TagName'];
                unset($value['TagName']);
            }
            if(!is_array($value)) {
                $s .= "<{$tagname}>".$value."</{$tagname}>";
            } else {
                $s .= "<{$tagname}>" . $this->array2xml($value, $level + 1)."</{$tagname}>";
            }
        }
        $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s);

        return $level == 1 ? $s."</xml>" : $s;
    }

    //向微信请求
    public function http_post($url, $param, $wxchat) {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        if (is_string($param)) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach ($param as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt ( $oCurl, CURLOPT_CUSTOMREQUEST, "POST" );
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl  , CURLOPT_POSTFIELDS, $strPOST);
        if($wxchat){
            curl_setopt($oCurl,CURLOPT_SSLCERT,$wxchat['api_cert']);
            curl_setopt($oCurl,CURLOPT_SSLKEY,$wxchat['api_key']);
            curl_setopt($oCurl,CURLOPT_CAINFO,$wxchat['api_ca']);
        }
        curl_setopt ( $oCurl, CURLOPT_FOLLOWLOCATION, 1 );
        curl_setopt ( $oCurl, CURLOPT_AUTOREFERER, 1 );
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

    //企业付款测试
    public function test($openid,$money){
        $data = array(
            'userid' => '10',		//用户ID   做更新状态使用
            'openid' =>$openid,		//收钱的人微信 OPENID
            'refundid' => 1,		//退款申请ID
            'money'    => $money,		//金额
            'desc'     => '退款测试',
        );

        $res = $this->wxbuild($data);
        print_r($res);
    }
}
header("Content-type:text/html;charset=utf-8");
$class  =   new CompanyController();
$class->test('oZdoF1C8EcHH6IFkPw-IgpcjQp_k','1.5');